package com.ljc.cjgl.service;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ljc.cjgl.entitiy.Scoring;
import com.ljc.cjgl.entitiy.TbTest;
import com.ljc.cjgl.form.ScoringForm;
import com.ljc.cjgl.repository.ScoringRepository;
import com.ljc.cjgl.repository.TestRepository;

@Service
public class ScoringService {
	@Autowired
	private ScoringRepository scoringDAO;
	@Autowired
	private TestRepository testDAO;
	public List<Scoring> findAll(){
		return scoringDAO.findAll();
	}

	public Page<Scoring> findAll(Specification<Scoring> specification, Pageable pageRequest) {
		return scoringDAO.findAll(specification, pageRequest);
	}

	public Scoring findById(Integer id) {
		Optional<Scoring> optional = scoringDAO.findById(id);
		if(optional.isPresent()) {
			return optional.get();
		}
		return null;
	}

	public List<TbTest> findAllTest() {
		return testDAO.findAll();
	}

	public TbTest findTestById(Integer testId) {
		Optional<TbTest> optional = testDAO.findById(testId);
		if(optional.isPresent()) {
			return optional.get();
		}
		return null;
	}
	
	@Transactional
	public void save(ScoringForm form) {
		Scoring model=new Scoring();
		if(form.getId()!=null) {
			model=findById(form.getId());
		}
		BeanUtils.copyProperties(form, model,"id","test");
		if(form.getTestId1()==null) {
			model.setTest(null);
		}else {
			model.setTest(new TbTest(form.getTestId1()));
		}
		scoringDAO.save(model);
	}
	
	public synchronized boolean delete(List<Scoring> scorings) {
		try {
			for (Scoring s : scorings) {
				scoringDAO.deleteById(s.getId());
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public List<Scoring> findByTestId(Integer testId) {
		return scoringDAO.findByTestId(testId);
	}
	
}
